package org.topteam.oschat.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.topteam.oschat.entity.User;
import org.topteam.oschat.service.IAuthService;
import org.topteam.oschat.service.IUserService;
import org.topteam.oschat.util.SpringUtils;

import com.alibaba.fastjson.JSON;

public class AuthServlet extends HttpServlet {

	private static final long serialVersionUID = 780546673064746545L;

	private IAuthService authService;
	private IUserService userService;

	@Override
	public void init() throws ServletException {
		authService = SpringUtils.getBean(IAuthService.class);
		userService = SpringUtils.getBean(IUserService.class);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userId = req.getParameter("userId");
		String password = req.getParameter("password");
		Auth auth = new Auth();
		if (userId == null || password ==null) {
			auth.setSuccess(false);
		} else {
			User user = userService.getUser(userId);
			if(user!=null && user.getPassword().equals(password)){
				auth.setSuccess(true);
				String token = req.getSession().getId();
				auth.setToken(token);
				authService.addToken(token, userId);
			}else{
				auth.setSuccess(false);
			}
		}
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.getWriter().write(JSON.toJSONString(auth));
	}

}
